<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="代理名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入区域代理名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="所属区域" prop="area">
        <el-input
          v-model="queryParams.area"
          placeholder="请输入所属区域"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
     
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:proxy:add']"
        >新增</el-button>
      </el-col>
     
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['business:proxy:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="proxyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="编号" align="center" prop="id" /> -->
      <el-table-column label="所属区域" align="center" prop="areaName" width="150">
        <template slot-scope="scope">
          {{scope.row.areaName?scope.row.areaName.replaceAll("#",""):""}}
        </template>
      </el-table-column>
      <el-table-column label="区域代理名称" align="center" prop="name" width="150" >
        <template slot-scope="scope">
          <el-button
              type="text"
              @click="handleShow(scope.row)"
            >{{scope.row.name}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" align="center" prop="phonenumber" width="120" />
      <el-table-column label="身份证号" align="center" prop="idcard" />
      <el-table-column label="身份证正面" align="center" prop="cardZheng" >
        <template slot-scope="scope">
          
          <el-image v-if="scope.row.cardZheng"
            style="width: 100px; height: auto"
            :src="scope.row.cardZheng" 
            :preview-src-list="[scope.row.cardZheng]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="身份证反面" align="center" prop="cardFan" >
        <template slot-scope="scope">
          <el-image  v-if="scope.row.cardFan"
            style="width: 100px; height: auto"
            :src="scope.row.cardFan" 
            :preview-src-list="[scope.row.cardFan]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="地址" align="center" prop="address" width="230" />
      <!-- <el-table-column label="经度" align="center" prop="x" />
      <el-table-column label="纬度" align="center" prop="y" /> -->
      <el-table-column label="状态" align="center" prop="state" >
        <template slot-scope="scope">
          {{stateOptions.find(a=>a.value == scope.row.state).label}}
        </template>
      </el-table-column>
      <el-table-column label="余额" align="center" prop="amount"  />
      <!-- <el-table-column label="收入" align="center" prop="inFee"  /> -->
      <!-- <el-table-column label="支出" align="center" prop="outFee"  /> -->
      <el-table-column label="创建时间" align="center" prop="createTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  width="250">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit" 
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete" 
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-coordinate" v-if="scope.row.state === '1'"
            @click="handleApprove(scope.row)"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets" 
            @click="handleOrderList(scope.row)"
          >接单记录</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改代理管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" :disabled="disabled">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="选择区域" prop="area">
              <el-cascader 
                  :value="form.areaList"
                  :options="areaOptions"
                  @change="areaChange"
                  style="width: 100%;"
                  :show-all-levels="true" :props="props"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区域代理名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入区域代理名称" />
            </el-form-item>
          </el-col>
          
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idcard">
              <el-input v-model="form.idcard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证正面" prop="cardZheng">
              <imageUpload v-model="form.cardZheng"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证反面" prop="cardFan">
              <imageUpload v-model="form.cardFan"/>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入地址" >
                <el-button slot="append" icon="el-icon-search" @click="searchLocation"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="位置" prop="loc">
              <baidu-map :center="center" :zoom="zoom" @ready="handler" class="map" @click="handlerMapClick">
              <!-- 控件将定位到地图的右上角 -->
              <bm-scale anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-scale>
              <!-- 平移缩放组件 -->
              <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
              <!-- 缩略图 -->
              <bm-overview-map anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :isOpen="true"></bm-overview-map>
              <!-- 定位 -->
              <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_LEFT" :showAddressBar="true"
                              :autoLocation="true"></bm-geolocation>
              <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']"
                          anchor="BMAP_ANCHOR_TOP_LEFT"></bm-map-type>
              <!-- 示例位置 -->
              <bm-marker :position="center" >
              </bm-marker>
            </baidu-map>
            </el-form-item>        
          </el-col>
          <el-col :span="12">
            
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经度" prop="x">
              <el-input v-model="form.x" placeholder="请输入经度" :readonly="true" />
            </el-form-item>        
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="y">
              <el-input v-model="form.y" placeholder="请输入纬度" :readonly="true"  />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="submitForm('2')" v-if="disabled && approved">通 过</el-button>
        <el-button type="warning" @click="submitForm('3')" v-if="disabled && approved">驳 回</el-button>
        <el-button type="primary" @click="submitForm" v-if="!disabled">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 订单管理对话框 -->
    <el-dialog title="订单管理" :visible.sync="orderShow" width="55%" append-to-body>
      <el-table v-loading="orderloading" :data="orderList" >
          <el-table-column label="订单编号" align="center" prop="num" width="160" >
          </el-table-column>
          <el-table-column label="订单信息" align="center" prop="attribute" show-overflow-tooltip/>
          <el-table-column label="预约时间" align="center" prop="orderTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="下单人" align="center" prop="username" />
          <el-table-column label="接单人" align="center" prop="receiveName" />
          <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat"  />
          <el-table-column label="备注" align="center" prop="remark" />
          <!-- <el-table-column label="应付" align="center" prop="payable" /> -->
          <el-table-column label="实付" align="center" prop="pay" />
        </el-table>
        
        <pagination
          v-show="orderTotal>0"
          :total="orderTotal"
          :page.sync="queryOrderParams.pageNum"
          :limit.sync="queryOrderParams.pageSize"
          @pagination="getOrderList"
        />
        <div slot="footer" class="dialog-footer" style="text-align:center;">
          <el-button @click="orderShow = false">返 回</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProxy, getProxy, delProxy, addProxy, updateProxy, exportProxy } from "@/api/business/proxy";
import ImageUpload from '@/components/ImageUpload';
import { treeArea } from "@/api/system/area";
import { listOrder, getOrder, delOrder, addOrder, updateOrder, exportOrder } from "@/api/business/order";

export default {
  name: "Proxy",
  components: {
    ImageUpload
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      orderloading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      orderShow: false,
      // 总条数
      total: 0,
      orderTotal: 0,
      // 代理管理表格数据
      proxyList: [],
      orderList: null,
      // 状态数据字典
      statusOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      disabled: false,
      approved: false,
      areaOptions:[],
      props:{
        value: 'id',
        label: 'name',
        expandTrigger: 'hover'
      },
      proxy: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        createId: null,
        area: null,
        idcard: null,
        cardZheng: null,
        cardFan: null,
        address: null,
        x: null,
        y: null
      },
      // 查询参数
      queryOrderParams: {
        pageNum: 1,
        pageSize: 10,
        num: null,
        detail: null,
        orderTime: null,
        userId: null,
        username: null,
       
      },
      stateOptions: [{
          value: '0',
          label: '未审核'
        }, {
          value: '1',
          label: '审核中'
        }, {
          value: '2',
          label: '审核通过'
        }, {
          value: '3',
          label: '驳回'
        }],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "区域代理名称不能为空", trigger: "blur" }
        ],
        
      },
      center: {
        lng: 0,
        lat: 0
      },
      zoom: 12,
      map: null,
      BMap: null
    };
  },
  created() {
    this.getList();
    this.getAreaTree();
    this.getDicts("tb_order_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询代理管理列表 */
    getList() {
      this.loading = true;
      listProxy(this.queryParams).then(response => {
        this.proxyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getAreaTree() {
      treeArea().then(response => {
        this.areaOptions = response.data;
      });
    },
    /** 查询订单管理列表 */
    getOrderList() {
      this.orderloading = true;
      this.queryOrderParams.params = {};
      this.queryOrderParams.proxyId = this.proxy.id;
      if (null != this.daterangeOrderTime && '' != this.daterangeOrderTime) {
        this.queryOrderParams.params["beginOrderTime"] = this.daterangeOrderTime[0];
        this.queryOrderParams.params["endOrderTime"] = this.daterangeOrderTime[1];
      }
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryOrderParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryOrderParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listOrder(this.queryOrderParams).then(response => {
        this.orderList = response.rows;
        this.orderTotal = response.total;
        this.orderloading = false;
      });
    },
    handleOrderList(row) {
      this.orderShow = true;
      this.proxy = row;
      this.getOrderList();
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        createId: null,
        createTime: null,
        area: null,
        idcard: null,
        cardZheng: null,
        cardFan: null,
        address: null,
        x: null,
        y: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.disabled = false;
      this.approved = false;
      this.open = true;
      this.title = "添加代理管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProxy(id).then(response => {
        this.form = response.data;
        let areaCode = response.data.area; 
        if (areaCode) {
          this.form.areaList = [areaCode.substr(0,2)+"0000", areaCode.substr(0,4)+"00", areaCode].map(a=>parseInt(a));
        }
        this.disabled = false;
        this.approved = false;
        this.open = true;
        this.title = "修改代理信息";
        this.center.lng = this.form.x;
        this.center.lat = this.form.y;
      });
    },
    areaChange(node){
      console.log(node)
      console.log(node[node.length -1 ])
      this.form.area =  node[node.length -1 ];
    },
    handleApprove(row) {
      const id = row.id || this.ids
      getProxy(id).then(response => {
        this.form = response.data;
        this.disabled = true;
        this.approved = true;
        this.open = true;
        this.title = "审核代理信息";

      });
    },
    handleShow(row) {
      const id = row.id || this.ids
      getProxy(id).then(response => {
        this.form = response.data;
        this.disabled = true;
        this.approved = false;
        this.open = true;
        this.title = "查看代理信息";
        this.center.lng = this.form.x;
        this.center.lat = this.form.y;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProxy(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.state = 2;
            addProxy(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除代理管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delProxy(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有代理管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportProxy(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        })
    },
    // 百度地图
    handler ({BMap, map}) {
      map.centerAndZoom('西安市', 12);
      map.enableScrollWheelZoom(true) // 开启鼠标滚轮缩放
      this.BMap = BMap;
      this.map = map;
    },
    searchLocation(){
      var local = new this.BMap.LocalSearch(this.map, {
        renderOptions:{map: this.map}
      });
      local.search(this.form.address);
    },
    handlerMapClick({type, target, point, pixel, overlay}){
      this.form.x = point.lng;
      this.form.y = point.lat;
    }
  }
};
</script>
<style scoped>
  
  .mapBox1 {
    line-height: 250px;
  }
  .map {
    opacity: 0.9;
    margin-right: 0px;
    height: 250px;
  }
 
</style>